//
//  ZHCopyLabel.m
//  ZHUIKit
//
//  Created by Basic on 2018/8/15.
//

#import "ZHCopyLabel.h"


@interface ZHCopyLabel ()
@property (nonatomic, strong) UITapGestureRecognizer *tapGesture;
@property (nonatomic, strong) UILongPressGestureRecognizer *longPressGesture;
@end

@implementation ZHCopyLabel
#pragma mark - system
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        _longPressCopy = YES;
        [self zh_setupUI];
    }
    return self;
}

- (BOOL)canBecomeFirstResponder {
    return YES;
}

-(BOOL)canPerformAction:(SEL)action withSender:(id)sender { //指定该UICopyLabel可以响应的方法
    if (action == @selector(copy:)) {
        return YES;
    }
    return NO;
}

#pragma mark - setter
-(void)setTapCopy:(BOOL)tapCopy {
    _tapCopy = tapCopy;
    if (tapCopy) {
        //支持 点击显示菜单
        if (!_tapGesture) {
            _tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onTapHandle:)];
            _tapGesture.numberOfTapsRequired = 1;
            [self addGestureRecognizer:_tapGesture];
        }
    } else {
        //不显示
        if (_tapGesture) {
            [self removeGestureRecognizer:_tapGesture];
            _tapGesture = nil;
        }
    }
}

-(void)setLongPressCopy:(BOOL)longPressCopy {
    _longPressCopy = longPressCopy;
    if (longPressCopy) {
        //支持 长按显示菜单
        if (!_longPressGesture) {
            _longPressGesture = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(onLongPressHandle:)];
            [self addGestureRecognizer:_longPressGesture];
        }
    } else {
        //不显示
        if (_longPressGesture) {
            [self removeGestureRecognizer:_longPressGesture];
            _longPressGesture = nil;
        }
    }
}

#pragma mark - private
/**
 初始化
 */
- (void)zh_setupUI {
    self.userInteractionEnabled = YES;
    [self setLongPressCopy:_longPressCopy];//默认
}

#pragma mark - Event
- (void)onTapHandle:(UITapGestureRecognizer *)sender {
    UIMenuController *menuVC = [UIMenuController sharedMenuController];
    if (!menuVC.isMenuVisible) {
        [self becomeFirstResponder];
        [menuVC setTargetRect:self.frame inView:self.superview];
        [menuVC setMenuVisible:YES animated:YES];
    }
}

- (void)onLongPressHandle:(UITapGestureRecognizer *)sender {
    UIMenuController *menuVC = [UIMenuController sharedMenuController];
    if (!menuVC.isMenuVisible) {
        [self becomeFirstResponder];
        [menuVC setTargetRect:self.frame inView:self.superview];
        [menuVC setMenuVisible:YES animated:YES];
    }
}

- (void)copy:(id)sender {
    [UIPasteboard generalPasteboard].string = self.text;
}
@end
